package org.hcf.api.controller;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.hcf.api.base.Helper;
import org.hcf.api.intf.ICallBack;
import org.hcf.api.tencent.callback.*;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Order(99)
@RestController
/** 腾讯云回调 */
public class CallBackController {
    @PostConstruct
    void init() {
        put(CallbackGroupCreateHandler.class);
        put(CallbackGroupDeleteHandler.class);
        put(CallbackGroupMemberJoinHandler.class);
        put(CallbackGroupMemberExitHandler.class);
        put(CallbackFriendMsgHandler.class);
        put(CallbackGroupMsgHandler.class);
    }

    <CALL extends ICallBack> void put(Class<CALL> cls) {
        try {
            callBackMap.put(cls.getSimpleName(), cls.newInstance());
        } catch (Throwable ex) {
        }
    }

    Map<String, ICallBack> callBackMap = new HashMap<>();

    //        @RequestParam("SdkAppid") long appid, @RequestParam("CallbackCommand") String command, @RequestParam("ClientIP") String clientIP, @RequestParam("OptPlatform") String platform, @RequestBody String body
    @CrossOrigin(origins = "*")
    @PostMapping("/callback")
    /** 腾讯云回调接收 */
    public JSONObject callback(HttpServletRequest request, @RequestBody String str) {
        if (!NumberUtil.isNumber(request.getParameter("SdkAppid")) || StrUtil.isBlank(request.getParameter("CallbackCommand")) || StrUtil.isBlank(request.getParameter("ClientIP")) || StrUtil.isBlank(request.getParameter("OptPlatform")))
            return toSuccess();
        long appid = Long.parseLong(request.getParameter("SdkAppid"));
        Enumeration<String> params = request.getParameterNames();
        JSONObject ps = new JSONObject();
        while (params.hasMoreElements()) {
            String key = params.nextElement();
            String value = request.getParameter(key);
            ps.put(key, value);
        }
        log.info("*** 收到腾讯云回调消息:" + ps + "\r\n" + str);

        if (appid != Helper.CONF.getAppId()) {
            log.error("腾讯云回调消息appId[" + appid + "]错误");
            return toSuccess();
        }
        String command = request.getParameter("CallbackCommand");
        String clientIP = request.getParameter("ClientIP");
        String platform = request.getParameter("OptPlatform"); //String platform
//        String body = request.getMethod();
        JSONObject data = JSONObject.parseObject(str);
        for (ICallBack callback : callBackMap.values()) {
            if (StrUtil.equalsIgnoreCase(command, callback.getCommand())) return callback.action(data);
        }
        log.error("腾讯云回调消息不支持CallbackCommand[" + command + "]命令的处理");
//        switch (command) {
//            case "C2C.CallbackAfterSendMsg":            //发单聊消息之后回调
//                return sendFriendMsg(data);
//            case "Group.CallbackAfterSendMsg":          //群内发言之后回调
//                return sendGroupMsg(data);
//            case "Group.CallbackAfterCreateGroup":      //创建群组之后回调
//                return createGroup(data);
//            case "Group.CallbackAfterNewMemberJoin":    //新成员入群之后回调
//                return memberJoin(data);
//            case "Group.CallbackAfterMemberExit":       //群成员离开之后回调
//                return memberExit(data);
//            case "Group.CallbackAfterGroupDestroyed":   //群组解散之后回调
//                return groupDestroyed(data);
//        }
        return toSuccess();
    }

    public JSONObject sendFriendMsg(JSONObject body) {
        log.info("收到发单聊消息之后回调:" + body);
//        JSONObject data = JSONObject.parseObject(body);
        return toSuccess();
    }

    public JSONObject sendGroupMsg(JSONObject data) {
        log.info("收到群内发言之后回调:" + data);
//        JSONObject data = JSONObject.parseObject(body);
        String groupId = data.getString("GroupId");
        return toSuccess();
    }

//    public Set<String> getGroupMember(String groupId){
//        JSONObject json = new JSONObject();
//        json.put("GroupId", groupId);
//        String res = HttpUtil.post(groupMemberUrl, json.toJSONString());
//        JSONObject memberJson = JSONObject.parseObject(res);
//
//    }

//    {
//        "CallbackCommand": "Group.CallbackAfterCreateGroup", // 回调命令
//            "GroupId" : "@TGS#2J4SZEAEL",
//            "Operator_Account": "group_root", // 操作者
//            "Owner_Account": "leckie", // 群主
//            "Type": "Public", // 群组类型
//            "Name": "MyFirstGroup", // 群组名称
//            "MemberList": [ // 初始成员列表
//        {
//            "Member_Account": "bob"
//        },
//        {
//            "Member_Account": "peter"
//        }
//    ],
//        "UserDefinedDataList": [ //用户建群时的自定义字段
//        {
//            "Key": "UserDefined1",
//                "Value": "hello"
//        },
//        {
//            "Key": "UserDefined2",
//                "Value": "world"
//        }
//    ],
//        "EventTime": 1670574414123//毫秒级别，事件触发时间戳
//    }

//    public JSONObject createGroup(JSONObject data) {
//        log.info("收到创建群组之后回调:" + data);
////        JSONObject data = JSONObject.parseObject(body);
//        if (!"Group.CallbackAfterCreateGroup".equals(data.getString("CallbackCommand"))) return toSuccess();
//        String groupId = data.getString("GroupId");
//        Iterable<String> ks = Caches.getCache(CacheConfig.PLUGIN_USER_QR).keys();
//        Set<Long> uids = new HashSet<>();
//        for (String k : ks) {
//            if (NumberUtil.isNumber(k)) uids.add(Long.parseLong(k));
//        }
//        String account = data.getString("Operator_Account");
//        if (NumberUtil.isNumber(account)) {
//            HashSet<String> groups = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(account, HashSet.class);
//            if (groups != null) groups.add(groupId);
//        }
//        JSONArray members = data.getJSONArray("MemberList");
//        Long uid = null;
//        for (int i = 0; i < members.size(); i++) {
//            JSONObject m = members.getJSONObject(i);
//            if (m != null && (uid = m.getLongValue("Member_Account")) != null) {
//                if (uids.contains(uid)) {
//                    HashSet<String> groups = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(uid.toString(), HashSet.class);
//                    if (groups != null) groups.add(groupId);
//                }
//            }
//        }
//
//        return toSuccess();
//    }

//    {
//        "CallbackCommand": "Group.CallbackAfterNewMemberJoin", // 回调命令
//            "GroupId" : "@TGS#2J4SZEAEL",
//            "Type": "Public", // 群组类型
//            "JoinType": "Apply", // 入群方式：Apply（申请入群）；Invited（邀请入群）
//            "Operator_Account": "leckie", // 操作者成员
//            "NewMemberList": [ // 新入群成员列表
//        {
//            "Member_Account": "jared"
//        },
//        {
//            "Member_Account": "tommy"
//        }
//    ],
//        "EventTime": 1670574414123//毫秒级别，事件触发时间戳
//    }

//    public JSONObject memberJoin(JSONObject data) {
//        log.info("收到新成员入群之后回调:" + data);
////        JSONObject data = JSONObject.parseObject(body);
//        if (!"Group.CallbackAfterNewMemberJoin".equals(data.getString("CallbackCommand"))) return toSuccess();
//        String groupId = data.getString("GroupId");
//        Iterable<String> ks = Caches.getCache(CacheConfig.PLUGIN_USER_QR).keys();
//        Set<Long> uids = new HashSet<>();
//        for (String k : ks) {
//            if (NumberUtil.isNumber(k)) uids.add(Long.parseLong(k));
//        }
//        JSONArray members = data.getJSONArray("NewMemberList");
//        Long uid = null;
//        for (int i = 0; i < members.size(); i++) {
//            JSONObject m = members.getJSONObject(i);
//            if (m != null && (uid = m.getLongValue("Member_Account")) != null) {
//                if (uids.contains(uid)) {
//                    HashSet<String> groups = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(uid.toString(), HashSet.class);
//                    if (groups != null) groups.add(groupId);
//                }
//            }
//        }
//
//        return toSuccess();
//    }

//    {
//        "CallbackCommand": "Group.CallbackAfterMemberExit", // 回调命令
//            "GroupId": "@TGS#2J4SZEAEL", // 群组 ID
//            "Type": "Public", // 群组类型
//            "ExitType": "Kicked", // 成员离开方式：Kicked-被踢；Quit-主动退群
//            "Operator_Account": "leckie", // 操作者
//            "ExitMemberList": [ // 离开群的成员列表
//        {
//            "Member_Account": "jared"
//        },
//        {
//            "Member_Account": "tommy"
//        }
//    ],
//        "EventTime": 1670574414123//毫秒级别，事件触发时间戳
//    }

//    public JSONObject memberExit(JSONObject data) {
//        log.info("收到群成员离开之后回调:" + data);
////        JSONObject data = JSONObject.parseObject(body);
//        if (!"Group.CallbackAfterMemberExit".equals(data.getString("CallbackCommand"))) return toSuccess();
//        String groupId = data.getString("GroupId");
//        Iterable<String> ks = Caches.getCache(CacheConfig.PLUGIN_USER_QR).keys();
//        Set<Long> uids = new HashSet<>();
//        for (String k : ks) {
//            if (NumberUtil.isNumber(k)) uids.add(Long.parseLong(k));
//        }
//        JSONArray members = data.getJSONArray("ExitMemberList");
//        Long uid = null;
//        for (int i = 0; i < members.size(); i++) {
//            JSONObject m = members.getJSONObject(i);
//            if (m != null && (uid = m.getLongValue("Member_Account")) != null) {
//                if (uids.contains(uid)) {
//                    HashSet<String> groups = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(uid.toString(), HashSet.class);
//                    if (groups != null) groups.remove(groupId);
//                }
//            }
//        }
//
//        return toSuccess();
//    }

//    public JSONObject groupDestroyed(JSONObject data) {
//        log.info("收到群组解散之后回调:" + data);
////        {
////            "CallbackCommand": "Group.CallbackAfterGroupDestroyed", // 回调命令
////                "Operator_Account": "administrator", //操作者
////                "GroupId" : "@TGS#2J4SZEAEL",
////                "Type": "Public", // 群组类型
////                "Owner_Account": "leckie", // 群主
////                "Name": "MyFirstGroup", // 群组名称
////                "MemberList" : [ //被解散的群组中的成员
////            {
////                "Member_Account": "leckie"
////            },
////            {
////                "Member_Account": "peter"
////            },
////            {
////                "Member_Account": "bob"
////            }
////    ],
////            "EventTime": 1670574414123//毫秒级别，事件触发时间戳
////        }
//        String groupId = data.getString("GroupId");
//        if (!"Group.CallbackAfterGroupDestroyed".equals(data.getString("CallbackCommand"))) return toSuccess();
//        Iterable<String> ks = Caches.getCache(CacheConfig.PLUGIN_USER_QR).keys();
//        Set<Long> uids = new HashSet<>();
//        for (String k : ks) {
//            if (NumberUtil.isNumber(k)) uids.add(Long.parseLong(k));
//        }
//        JSONArray members = data.getJSONArray("MemberList");
//        Long uid = null;
//        for (int i = 0; i < members.size(); i++) {
//            JSONObject m = members.getJSONObject(i);
//            if (m != null && (uid = m.getLongValue("Member_Account")) != null) {
//                if (uids.contains(uid)) {
//                    HashSet<String> groups = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(uid.toString(), HashSet.class);
//                    if (groups != null) groups.remove(groupId);
//                }
//            }
//        }
//
//        return toSuccess();
//    }

    public static JSONObject toSuccess() {
        JSONObject json = new JSONObject();
        json.put("ActionStatus", "OK");
        json.put("ErrorInfo", "OK");
        json.put("ErrorCode", 0);
        return json;
    }
}
